/* 
	商品管理 - goods
 */

/* ------------------------------------------------------------------------------------
	模块导入
------------------------------------------------------------------------------------ */
// 第三方模块 - express
const express = require('express')

/* ------------------------------------------------------------------------------------
	常量、变量、方法
------------------------------------------------------------------------------------ */
// 新建路由
const goodsRouter = express.Router()
/* ------------------------------------------------------------------------------------
	路由配置
------------------------------------------------------------------------------------ */

/* 
|字段|类型|默认值|注释|主键|
|:----|:-------|:---|---|------|---|
|shop_id|int(10) unsigned||PRI|所属店铺主键id|
|category_id|int(10) unsigned|||分类id|
|goods_name|varchar(255)|		|	|商品名|
|goods_price|float(10,2) unsigned|0.00|商品价格|
|goods_info|varchar(255)|		|	|商品描述|
|goods_id|int(10) unsigned|PRI|商品主键id|
|goods_img|varchar(255)||商品图|
|status|enum('在售','下架')|在售||商品状态('在售','下架')默认在售|
 */

/* ------------------------------------------------------------------------------------
	GET
------------------------------------------------------------------------------------ */

// 根据id获取
goodsRouter.get('/getById', async (req, res) => res.getById('goods', 'goods_id'))

// 根据分类id获取
goodsRouter.get('/getByCategoryId', async (req, res) => res.getById('goods', 'category_id'))

// 根据店铺id获取
goodsRouter.get('/getByShopId', async (req, res) => res.getById('goods', 'shop_id'))

// 获取商品列表数据
goodsRouter.get('/get', async (req, res) => {
	console.log('获取商品')
	// 参数
	const goods_name = req.query.goods_name ? req.query.goods_name : ''
	const pagenum = req.query.pagenum ? req.query.pagenum : 1
	const pagesize = req.query.pagesize ? req.query.pagesize : 10

	// 基础 sql 语句
	let sql = `SELECT * FROM goods`

	// 模糊匹配商品名
	// 无查询条件，匹配全部
	if (goods_name !== '') sql += ` WHERE goods_name LIKE '%${goods_name}%'`

	// 发送 sql
	const pageindex = (pagenum - 1) * pagesize
	const goods = await res.execSql(sql + ` LIMIT ${pageindex},${pagesize}`)

	// 总条数
	const {
		total
	} = (await res.execSql(`SELECT COUNT(goods_id) AS total FROM goods`))[0]

	// 总页数
	const totalPage = Math.ceil(total / pagesize)

	res.sendResult({
		goods,
		total,
		pagenum,
		totalPage
	}, 200, '获取成功')
})


/* ------------------------------------------------------------------------------------
	POST
------------------------------------------------------------------------------------ */

// 新增商品
goodsRouter.post('/add', (req, res) => {
	console.log('添加商品')
	// 参数
	const {
		shop_id,
		goods_name,
		goods_price,
		category_id
	} = req.body

	// 安全阻断
	if (!shop_id || (!goods_name || goods_name === '') || !goods_price || !category_id) return res
		.sendResult(null, 400, '请提供完整信息')

	res.execSql(
		`INSERT INTO goods(shop_id, goods_name, goods_price, category_id) VALUES('${shop_id}', '${goods_name}','${goods_price}','${category_id}')`
	)
	res.sendResult(null, 200, '添加成功')
	/* 返回数据格式
		 OkPacket {
			 fieldCount: 0,
			 affectedRows: 1,
			 insertId: 12,
			 serverStatus: 2,
			 warningCount: 0,
			 message: '',
			 protocol41: true,
			 changedRows: 0
		 }
	 */
	// insertID插入的记录id
})

// 修改商品信息
goodsRouter.post('/edit', async (req, res) => {
	console.log('修改商品信息')
	// 参数
	const {
		id
	} = req.body

	// 安全阻断
	if (!id) return res.sendResult(null, 400, '请提供id')
	const goods = await res.execSql(`SELECT * FROM goods WHERE goods_id = '${id}'`)
	if (goods.length <= 0) return res.sendResult(null, 400, '无此用户！请检查id是否正确')

	// 基础 sql
	let sql = `UPDATE goods SET `

	const filedArr = ['category_id', 'goods_name', 'goods_price', 'goods_info', 'goods_img']

	// 遍历加工
	for (let key in req.body) {
		if (filedArr.indexOf(req.body[key] !== -1)) sql += `${key} = '${req.body[key]}',`
	}
	sql.substring(0, sql.length - 1)
	// 添加条件
	sql += ` WHERE goods_id='${id}'`

	// 发送 sql
	res.execSql(sql).sendResult(null, 200, `修改成功`)
})

// 删除商品
goodsRouter.post('/delete', async (req, res) => {
	console.log('删除商品')
	// 参数
	const {
		id
	} = req.body

	// 安全阻断
	if (!id) return res.sendResult(null, 400, '请提供id')
	const goods = await res.execSql(`SELECT * FROM good WHERE goods_id = '${id}'`)
	if (goods.length <= 0) return res.sendResult(null, 400, '无此商品！请检查id是否正确')

	// 发送 sql
	res.execSql(`UPDATE goods SET status = '下架' WHERE goods_id = '${id}'`)
	res.sendResult(null, 200, '删除成功')
})



/* ------------------------------------------------------------------------------------
	导出路由
------------------------------------------------------------------------------------ */
module.exports = goodsRouter
